<template>
  <div class="app-container">
    <!-- 搜索区 -->
    <div class="filter-container">
      <el-form :inline="true" :model="temp" class="demo-form-inline">
        <el-form-item label="客户姓名" id="116" v-if="filterIsShow(116)">
          <el-input
            v-model="listQuery.name"
            placeholder="客户姓名"
            class="filter-item"
            @keyup.enter.native="handleFilter"
          />
        </el-form-item>
        <el-form-item label="客户电话" id="117" v-if="filterIsShow(117)">
          <el-input
            v-model="listQuery.phone"
            placeholder="客户电话"
            class="filter-item"
            @keyup.enter.native="handleFilter"
          />
        </el-form-item>
        <el-form-item label="宝贝品种" id="109" v-if="filterIsShow(109)">
          <el-input
            v-model="listQuery.petVariety"
            placeholder="宝贝品种"
            class="filter-item"
            @keyup.enter.native="handleFilter"
          />
        </el-form-item>
        <el-form-item label="宝贝姓名" id="106" v-if="filterIsShow(106)">
          <el-input
            v-model="listQuery.petName"
            placeholder="宝贝姓名"
            class="filter-item"
            @keyup.enter.native="handleFilter"
          />
        </el-form-item>
        <el-form-item label="产品" id="113" v-if="filterIsShow(113)">
          <el-select
            v-model="listQuery.listRetailProduct"
            class="filter-item"
            placeholder="产品"
          >
            <el-option
              v-for="item in listRetailProduct"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="客户渠道" id="101" v-if="filterIsShow(101)">
          <el-select
            v-model="listQuery.channel"
            class="filter-item"
            placeholder="客户渠道"
            clearable
          >
            <el-option
              v-for="(item, i) in channelOptions"
              :key="i"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="服务方案" id="102" v-if="filterIsShow(102)">
          <el-select
            v-model="listQuery.servicePlanName"
            class="filter-item"
            placeholder="服务方案"
            clearable
          >
            <el-option
              v-for="item in listRetailServicePlan"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="开始日期">
          <el-date-picker
            v-model="listQuery.startDate"
            type="date"
            placeholder="选择开始日期"
            value-format="yyyy-MM-dd HH:mm:ss"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束日期">
          <el-date-picker
            v-model="listQuery.endDate"
            type="date"
            placeholder="选择结束日期"
            value-format="yyyy-MM-dd 23:59:59"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>
      <el-button
        v-waves
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
        >搜索</el-button
      >
      <el-button
        class="filter-item"
        style="margin-left: 10px"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >
        新增
      </el-button>
      <el-button
        v-waves
        :loading="downloadLoading"
        class="filter-item"
        type="primary"
        icon="el-icon-download"
        @click="handleDownload"
        >导出
      </el-button>
    </div>
    <!-- 表格区 -->

    <el-table
     empty-text='暂无数据'
      :key="tableKey"
      :row-class-name="rowClassName"
      v-loading="listLoading"
      :data="tableData.records"
      border
      fit
      highlight-current-row
      style="width: 100%"
      @sort-change="sortChange"
    >
      <el-table-column
        label="ID"
        prop="id"
        sortable="custom"
        align="center"
        width="80"
      />
      <el-table-column
        label="状态"
        align="center"
        width="150px"
      >
      <template slot-scope="{ row}">
      {{ row.isInvalid==0?'正常':'作废' }}
      </template>
    </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="160px"
      />
      <el-table-column
        label="宝贝姓名"
        align="center"
        prop="petName"
        width="95"
        id="106" v-if="filterIsShow(106)"
      />
      <el-table-column
        label="宝贝品种"
        align="center"
        prop="petVariety"
        width="95"
        id="109" v-if="filterIsShow(109)"
      />

      <el-table-column
        label="客户姓名"
        align="center"
        prop="name"
        width="80px"
        id="116" v-if="filterIsShow(116)"
      />
      <el-table-column
        label="客户电话"
        align="center"
        prop="phone"
        width="95"
        id="117" v-if="filterIsShow(117)"
      />
      <el-table-column
        label="客户地址"
        align="center"
        prop="customerAddress"
        width="110px"
        id="115" v-if="filterIsShow(115)"
      />
      <el-table-column
        label="消费金额"
        align="center"
        prop="totalAmount"
        width="110px"
        id="121" v-if="filterIsShow(121)"
      />
      <!-- <el-table-column
        label="殡葬师"
        align="center"
        prop="morticianUserList"
        width="110px"
      /> -->
 <!-- 自定义数组字段列 -->
 <el-table-column label="殡葬师" align="center" id="105" v-if="filterIsShow(105)">
    <template slot-scope="scope">
      <div v-if="scope.row.morticianUserList?.length">
        <el-tag 
          v-for="member in scope.row.morticianUserList" 
          :key="member.id"
          style="margin: 2px"
        >
          {{ member.name?member.name:'未命名' }}
        </el-tag>
      </div>
      <span v-else>暂无人员</span>
    </template>
</el-table-column>
      <!-- <el-table-column label="预约时间" align="center" prop="createTime" width="150px" />
      <el-table-column label="客户渠道" align="center" prop="channel" width="150px" />
      <el-table-column label="客户地址" align="center" prop="customerAddress" width="110px" />
      <el-table-column label="客户姓名" align="center" prop="name" width="80px" />
      <el-table-column label="客户电话" align="center" prop="phone" width="95" />
      <el-table-column label="是否到店" align="center" prop="isArrive" width="100" />
     
      <el-table-column label="宝贝性别" align="center" prop="petSex" width="95" />
      <el-table-column label="宝贝年龄" align="center" prop="petAge" width="95" />
      <el-table-column label="宝贝体重（斤）" align="center" prop="petWeight" width="95" />
      <el-table-column label="宝贝离世原因" align="center" prop="petDeadReason" width="95" />
      <el-table-column label="服务方案" align="center" prop="retailServicePlanName" width="95" />
      <el-table-column label="服务金额" align="center" prop="servicePlanPrice" width="95" />
      <el-table-column label="骨灰盅" align="center" prop="ashUrnName" width="95" />
      <el-table-column label="骨灰盅金额" align="center" prop="ashUrnPrice" width="95" />
      <el-table-column label="产品" align="center" prop="productName" width="95" />
      <el-table-column label="产品价格" align="center" prop="productPrice" width="95" />
      <el-table-column label="体重区间" align="center" prop="weightCostName" width="95" />
      <el-table-column label="体重区间价格" align="center" prop="weightCostPrice" width="95" />
      <el-table-column label="优惠" align="center" prop="discount" width="95" />
      <el-table-column label="增加车费" align="center" prop="addCarFee" width="95" />
      <el-table-column label="总金额" align="center" prop="totalAmount" width="95" />
      <el-table-column label="收款方式" align="center" prop="payType" width="95" /> -->
      <el-table-column label="备注" align="center" prop="remark" width="95" id="122" v-if="filterIsShow(122)"/>
      <el-table-column
        label="操作"
        fixed="right"
        align="center"
       
        class-name="small-padding fixed-width"
        width='200'
      >
        <template slot-scope="{ row, $index }">
          <el-button type="primary" size="mini" @click="handleUpdate(row,'view')">
            查看
          </el-button>
        
          <el-button
          v-if="row.isInvalid == 0"
          size="mini"
          type="danger"
          @click="handleInvalidRecover(row, 1)"
        >
          作废
        </el-button>
        <el-button
          v-if="userInfo.isShopLeader !== 0 && row.isInvalid == 1"
          size="mini"
          type="success"
          @click="handleInvalidRecover(row, 0)"
        >
          恢复
        </el-button>
          <!-- <el-button v-if="row.status != 'deleted'" size="mini" type="danger" @click="handleDelete(row, $index)">
            删除
          </el-button> -->
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页区 -->
    <pagination
      v-show="tableData.total > 0"
      size="small"
      @size-change="handleSizeChange"
      @current-change="handlePageChange"
      :current-page="Number(tableData.current)"
      :page-sizes="[10, 50, 100]"
      :page-size="Number(tableData.size)"
      layout="total, sizes, prev, pager, next, jumper"
      :total="Number(tableData.total)"
    />
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-width="120px"
        label-position="right"
        class="demo-form-inline"
        :inline="true"
        :disabled="dialogStatus!=='create'?true:false"
      >
        <el-form-item label="客户渠道" id="101" v-if="filterIsShow(101)">
          <el-select
            v-model="temp.channel"
            class="filter-item"
            placeholder="请选择客户渠道"
            clearable
          >
            <el-option
              v-for="(item, i) in channelOptions"
              :key="i"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="服务方案" id="102" v-if="filterIsShow(102)">
          <el-select
            v-model="temp.servicePlanId"
            class="filter-item"
            placeholder="请选择服务方案"
            clearable
          >
            <el-option
              v-for="item in listRetailServicePlan"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="服务金额" id="103" v-if="filterIsShow(103)">
          <el-input
            v-model.number="temp.servicePlanPrice"
            placeholder="请输入服务金额"
            clearable
          />
        </el-form-item>
        <el-form-item label="殡葬师" id="105" v-if="filterIsShow(105)">
          <el-select
          multiple
          v-model="temp.morticianIds"
          class="filter-item"
          placeholder="请输入殡葬师"
          @change="productChange"
        >
          <el-option
            v-for="item in BurialListDatas"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
          <!-- <el-input
            v-model="temp.morticianIds"
            placeholder="请输入殡葬师"
            clearable
          /> -->
        </el-form-item>
        <el-form-item label="宝贝姓名" id="106" v-if="filterIsShow(106)">
          <el-input
            v-model="temp.petName"
            placeholder="请输入宝贝姓名"
            clearable
          />
        </el-form-item>
        <el-form-item label="宝贝年龄" id="107" v-if="filterIsShow(107)">
          <el-input
            v-model="temp.petAge"
            placeholder="请输入宝贝年龄"
            clearable
          />
        </el-form-item>
        <el-form-item label="宝贝离世原因" id="108" v-if="filterIsShow(108)">
          <el-input
            v-model="temp.petDeadReason"
            placeholder="请输入宝贝离世原因"
            clearable
          />
        </el-form-item>
        <el-form-item label="宝贝品种" id="109" v-if="filterIsShow(109)">
          <el-select
            v-model="temp.petVariety"
            class="filter-item"
            placeholder="请选择客户渠道"
            clearable
          >
            <el-option
              v-for="(item, i) in petVarietyOptions"
              :key="i"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="宝贝性别" id="110" v-if="filterIsShow(110)">
          <el-select
            v-model="temp.petSex"
            class="filter-item"
            placeholder="请选择宝贝性别"
          >
            <el-option label="弟弟" value="弟弟" />
            <el-option label="妹妹" value="妹妹" />
          </el-select>
        </el-form-item>
        <el-form-item label="宝贝体重（斤）" id="111" v-if="filterIsShow(111)">
          <el-input
            v-model="temp.petWeight"
            placeholder="请输入宝贝体重"
            clearable
          />
        </el-form-item>
        <el-form-item label="体重区间价格" id="111" v-if="filterIsShow(111)">
          <el-input
            v-model.number="temp.weightCostPrice"
            placeholder="请输入体重区间价格"
            clearable
          />
        </el-form-item>
        <el-form-item label="骨灰盅" id="112" v-if="filterIsShow(112)">
          <el-select
            v-model="temp.ashUrnId"
            class="filter-item"
            placeholder="请选择骨灰盅"
            clearable
          >
            <el-option
              v-for="item in cineraryUrnListDatas"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="骨灰盅金额" v-if="temp.ashUrnPrice>0&&filterIsShow(102)" >
          <el-input
            v-model.number="temp.ashUrnPrice"
            placeholder="请输入骨灰盅金额"
            clearable
          />
        </el-form-item>

        <el-form-item label="产品" id="113" v-if="filterIsShow(113)">
          <el-select
            multiple
            v-model="temp.productIds"
            class="filter-item"
            placeholder="请选择产品"
            @change="productChange"
          >
            <el-option
              v-for="item in listRetailProduct"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="产品价格">
          <el-input
            v-model="temp.productPrice"
            placeholder="请输入产品价格"
            clearable
          />
        </el-form-item> -->
        <el-form-item label="加购产品金额" id="113" v-show="temp.addProductPrice>0&&filterIsShow(113)" >
          <el-input
            v-model.number="temp.addProductPrice"
            placeholder="请输入加购产品金额"
            clearable
          />
        </el-form-item>

        <el-form-item label="是否到店" id="114" v-if="filterIsShow(114)">
          <el-select
            v-model="temp.isArrive"
            class="filter-item"
            placeholder="是否到店"
            clearable
          >
            <el-option label="无" value="无" />
            <el-option label="是" value="是" />
            <el-option label="否" value="否" />
          </el-select>
        </el-form-item>
        <el-form-item label="客户地址" id="115" v-if="filterIsShow(115)">
          <el-input
            v-model="temp.customerAddress"
            placeholder="请输入客户地址"
            clearable
          />
        </el-form-item>
        <el-form-item label="客户姓名" id="116" v-if="filterIsShow(116)">
          <el-input
            v-model="temp.name"
            placeholder="请输入客户姓名"
            clearable
          />
        </el-form-item>
        <el-form-item label="客户电话" id="117" v-if="filterIsShow(117)">
          <el-input
            v-model="temp.phone"
            placeholder="请输入客户电话"
            clearable
          />
        </el-form-item>
        <el-form-item label="收款方式" id="118" v-if="filterIsShow(118)">
          <el-input
            v-model="temp.payType"
            placeholder="请输入收款方式"
            clearable
          />
        </el-form-item>
        <el-form-item label="优惠" id="119" v-if="filterIsShow(119)">
          <el-input
            v-model.number="temp.discount"
            placeholder="请输入优惠"
            clearable
          />
        </el-form-item>
        <el-form-item label="增加车费" id="120" v-if="filterIsShow(120)">
          <el-input
            v-model.number="temp.addCarFee"
            placeholder="请输入增加车费"
            clearable
          />
        </el-form-item>
        <el-form-item label="总金额" id="121" v-if="filterIsShow(121)">
          <!-- <el-input
            v-model="temp.totalAmount"
            placeholder="请输入总金额"
            clearable
          /> -->
          <el-input
          v-model.number="temp.totalAmount"
          placeholder="请输入总价"
        >
          <!-- 在输入框尾部添加按钮 -->
          <template #append>
            <el-button 
              icon="el-icon-calculator" 
              @click="calculateTotal"
            >
              计算
            </el-button>
          </template>
        </el-input>
        </el-form-item>
       
       
        <!-- <el-form-item label="Imp">
           <el-rate
             v-model="temp.importance"
             :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
             :max="3"
             style="margin-top: 8px"
           />
         </el-form-item> -->
        <el-form-item label="备注" id="122" v-if="filterIsShow(122)">
          <el-input
            v-model="temp.remark"
            :autosize="{ minRows: 2, maxRows: 4 }"
            type="textarea"
            placeholder="请填写备注"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button
          type="primary"
          @click="dialogStatus === 'create' ? createData() : updateData()"
        >
         确认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  exportExcel,
  retailCustomerAdd,
  retailCustomerExportExcel,
  retailCustomerListQuery,
  retailCustomerUpdate,
  getCineraryUrnList,
  getListQuery,
  create,
  update,
  deleteData,
  invalidRecoverApi,
  getListQueryBurial,
  getSetOrderList
} from "@/api/customerInformation";
import { retailServicePlanList } from "@/api/retailServicePlan";
import { retailProductList } from "@/api/retailProduct";
import { retailWeightCostList } from "@/api/retailWeightCost";
import { downloadFile } from "@/utils/yangUtils";
import waves from "@/directive/waves"; // waves directive
import { parseTime } from "@/utils";
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
import customerInformation from "@/utils/customerInformation";
import { mapState } from "vuex";

const calendarTypeOptions = [
  { key: "CN", display_name: "China" },
  { key: "US", display_name: "USA" },
  { key: "JP", display_name: "Japan" },
  { key: "EU", display_name: "Eurozone" },
];

// arr to obj, such as { CN : "China", US : "USA" }
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name;
  return acc;
}, {});

export default {
  name: "ComplexTable",
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: "success",
        draft: "info",
        deleted: "danger",
      };
      return statusMap[status];
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type];
    },
  },
  data() {
    return {
      setOrderListDatas:[],//设置字段数据
      BurialListDatas:[],//员工列表
      dialogType:'',
      mealProductId: [], //套餐内产品id
      customerInformationPermission: [],
      petVarietyOptions: ["狗狗", "猫咪", "小宠", "异宠", "无"],
      channelOptions: ["宠物医院", "其他", "抖音", "大众点评", "美团", "无"],
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        pageNum: 1,
        pageSize: 20,
        //         channel: "",
        //         petVariety: "",
        //         petSex: "",
        //         petWeight: "",
        //         servicePlanId: "",
        //         servicePlanPrice: "",
        //         ashUrnId: "",
        //         ashUrnPrice: "",
        //         productIds: "",
        //         productPrice: "",
        //         weightCostId: "",
        //         weightCostPrice: "",
        //         isArrive: "",
        //         customerAddress: "",
        //         name: "",
        //         phone: "",
        //         petName: "",
        //         petAge: "",
        //         petDeadReason: "",
        //         discount: "",
        //         addCarFee: "",
        //         totalAmount: "",
        //         payType: "",
        //         remark: "",
        startDate: "",
        endDate: "",
      },
      importanceOptions: [1, 2, 3],
      calendarTypeOptions,
      sortOptions: [
        { label: "ID Ascending", key: "+id" },
        { label: "ID Descending", key: "-id" },
      ],
      statusOptions: ["published", "draft", "deleted"],
      showReviewer: false,
      temp: {
        morticianIds: [], //殡葬师(多个)
        channel: "",
        petVariety: "",
        petSex: "",
        petWeight: "",
        servicePlanId: "",
        servicePlanPrice: 0,
        ashUrnId: "",
        ashUrnPrice:0,
        productIds: "",
        // productPrice: "",//产品价格
        addProductPrice: 0, //加购产品金额
        weightCostId: "",
        weightCostPrice: 0,
        isArrive: "",
        customerAddress: "",
        name: "",
        phone: "",
        petName: "",
        petAge: "",
        petDeadReason: "",
        discount: 0,
        addCarFee: 0,
        totalAmount: 0,
        payType: "",
        remark: "",
        totalAmount:0,//计算出的总价
      },
      dialogFormVisible: false,
      dialogStatus: "",
      textMap: {
        update: "编辑",
        create: "新增",
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        type: [
          { required: true, message: "type is required", trigger: "change" },
        ],
        timestamp: [
          {
            type: "date",
            required: true,
            message: "timestamp is required",
            trigger: "change",
          },
        ],
        title: [
          { required: true, message: "title is required", trigger: "blur" },
        ],
      },
      downloadLoading: false,
      listRetailServicePlan: [],
      listRetailProduct: [],
      listRetailWeightCost: [],

      cineraryUrnListDatas: [],
      tableData: {},
    };
  },
  watch: {
    "temp.petWeight"(newValue, oldValue) {
      this.temp.weightCostPrice = 0;

    
      const result = this.findPriceByValue(this.listRetailWeightCost, newValue);
      console.log(result); // 输出: 400
      if (!result) {
        // this.$notify({
        //   title: "Success",
        //   message: "该体重区间未设置价格",
        //   type: "warning",
        //   duration: 2000,
        // });
      } else {
        this.temp.weightCostPrice = result;
      }
    },
    "temp.weightCostId"(newValue, oldValue) {
      const filterDatas = this.listRetailWeightCost.filter(
        (item) => item.id === newValue
      )[0];
      this.temp.weightCostPrice = filterDatas?.price;
    },

    // "temp.productIds"(newValue, oldValue) {
    //   // const filterDatas = this.listRetailProduct.filter(
    //   //   (item) => item.id === newValue
    //   // )[0];
    //   const result =newValue.forEach((item1) =>
    //   this.listRetailProduct.some((item2) => {
    //         if (item2.id === item1) {
    //           this.temp.addProductPrice=item2.price;//加购产品金额
    //         }
    //       })
    //     );

    //   // this.temp.productPrice = filterDatas.price;

    //   // this.temp.productList = filterDatas.price;

    // },

    "temp.servicePlanId"(newValue, oldValue) {
      const filterDatas = this.listRetailServicePlan?.filter(
        (item) => item.id === newValue
      )[0];
      this.temp.servicePlanPrice = filterDatas?.price; //服务方案价格
      this.temp.ashUrnId = filterDatas.ashUrnId; //套餐内的骨灰盅

      if (filterDatas) {
        this.mealProductId = filterDatas.productList?.map(
          (product) => product.id
        ); // 设置套餐内已绑定的产品 IDs
        this.temp.productIds = this.mealProductId;
        // 过滤出两个数组中 id 相同的项
        const result = this.temp.productIds.forEach((item1) =>
          this.listRetailProduct.some((item2) => {
            if (item2.id === item1) {
              item2.name = `${item2.name}(套餐内产品)`;
            }
          })
        );

        this.cineraryUrnListDatas.some((item2) => {
          if (item2.id === this.temp.ashUrnId) {
            item2.name = `${item2.name}(套餐内产品)`;
          }
        });

        const price = filterDatas.productList?.map((product) => product.price); // 设置已绑定的产品 IDs
        this.temp.productPrice = price?.reduce(
          (accumulator, currentValue) => accumulator + currentValue,
          0
        );

      }
    },

    "temp.ashUrnId"(newValue, oldValue) {
      this.temp.ashUrnPrice =0;

      const filterDatas = this.cineraryUrnListDatas.filter(
        (item) =>{
          if(!item.name.includes("(套餐内产品)")&&item.id === newValue){
            this.temp.ashUrnPrice = item.price;
          }
        }
      );
      // this.temp.ashUrnPrice = filterDatas?.price;
    },
    "temp.totalAmount"(newValue, oldValue){
      if(newValue< this.totalAmount ){//用户输入的总价小于计算出的价格
          this.temp.discount=this.totalAmount-newValue
        }
    }
  },
  computed: {
    ...mapState({
      userInfo: (state) => state.user.userInfo,
    }),
    filterCusPermission() {
      const options = Object.assign({}, defaultOptions, this.options);
      options.initialEditType = this.mode;
      options.height = this.height;
      options.language = this.language;
      return options;
    },
    filterIsShow() {
      // 返回的函数可以接收参数
      return (id) => {
        return this.setOrderListDatas.includes(id)
      };
    }
  },

 async mounted() {
  await  this.getListQuery();

    this.getSetOrderList();

    const filter = customerInformation.find((item) => item.eName === "channel");
    this.customerInformationPermission = customerInformation;
    // this.getList();

    this.getListRetailServicePlan();
    this.getListRetailProduct();
    this.getListRetailWeightCost();
    this.getCineraryUrnList();
    this.getListQueryBurial();


    
  },
  methods: {

    async getSetOrderList() {
      this.listLoading = true;
      await getSetOrderList().then((response) => {
        this.setOrderListDatas = response.data.map((item)=>{
          if(item.status==1){
            return item.field
          }
          
        });
        console.log("🍓666",this.setOrderListDatas)
        this.listLoading = false;
      });
    },
    rowClassName({ row }) {
    return row.isInvalid ? 'disabled-row' : '';
  },
    async handleInvalidRecover(row,value){
      
      // invalidRecoverApi({isInvalid:value,id:row.id}).then((response) => {
      await invalidRecoverApi(row.id).then((response) => {

        this.listLoading = true;
        this.$notify({
          title: "Success",
          message:value==0?'恢复成功':'作废成功',
          type: "出库成功",
          duration: 2000,
        });
      });
      await this.getListQuery();
    },
    calculateTotal() {//计算总价
      // 1. 验证输入是否为数字
      // if (isNaN(this.temp.totalAmount)) {
      //   this.$message.error("请输入有效的数字！");
      //   return;
      // }
      // 2. 计算总价
      this.totalAmount = 
        Number(this.temp.servicePlanPrice) +
        Number(this.temp.ashUrnPrice)+
        Number(this.temp.addProductPrice)+
        Number(this.temp.weightCostPrice)+
        Number(this.temp.addCarFee)-
        Number(this.temp.discount)
        ;
        this.temp.totalAmount =   this.totalAmount 
       
    },
    getNonMatchingItems(arr1, arr2) {
      return arr1.filter((item1) => !arr2.some((item2) => item2 === item1));
    },
    // 检测第一个数组是否包含第二个数组的所有元素
    containsAllElements(arr1, arr2) {
      return arr2.every((item) => arr1.includes(item));
    },
    getAllCheckedProductsPrice(array1, array2) {
      //计算勾选的所有套餐总金额
      // 对比两个数组，对 array2 中匹配项的所有 price 字段进行累加
      let totalPrice = 0;

      array1.forEach((item1) => {
        // 在 array2 中查找所有 id 相同的项
        const matchedItems = array2.filter((item2) => item2.id === item1);
        if (matchedItems.length > 0) {
          // 累加所有匹配项的 price
          matchedItems.forEach((item) => {
            totalPrice += item.price;
            console.log(item, totalPrice);
          });
        }
      });

      if (this.temp.productPrice < totalPrice) {
        return totalPrice - this.temp.productPrice;
      }
      return 0;
    },
    productChange(value) {
      //产品逻辑:1.套餐内产品,不显示价格;2.用户勾选了其他产品,显示加购产品金额;3.用户取消套餐内产品,加购了其他产品时,高于套餐内产品设定的金额,价格显示在加购产品金额,低于时,加购产品金额显示0
      let outOfPackageProductId = this.getNonMatchingItems(
        value,
        this.mealProductId
      );
      const isContainsAllElements = this.containsAllElements(
        value,
        this.mealProductId
      ); //判断套餐内产品是否改变
      console.log(isContainsAllElements); // 输出: true

      if (!isContainsAllElements) {
        this.temp.addProductPrice = this.getAllCheckedProductsPrice(
          value,
          this.listRetailProduct
        );
      } else {
        let totalPrice = 0;

        outOfPackageProductId?.forEach((id) => {
          // 在 array2 中查找所有 id 相同的项
          const matchedItems = this.listRetailProduct.filter(
            (item2) => item2.id === id
          );
          if (matchedItems.length > 0) {
            // 累加所有匹配项的 price
            matchedItems.forEach((item) => {
              totalPrice += item.price;
            });
          }
        });
        this.temp.addProductPrice = totalPrice;

      }
    },
    // 过滤出包含 39 的区间，并返回对应的 price
    findPriceByValue(data, target) {
      // 遍历数组
      for (const item of data) {
        // 检查是否存在 name 字段
        if (item.name) {
          // 将 name 字段拆分为最小值和最大值
          const [min, max] = item.name.split("-").map(Number);
          // 判断 target 是否在区间内
          if (target > min && target <= max) {
            return item.price; // 返回对应的 price
          } else {
          }
        }
      }
      // 如果没有找到匹配的区间，返回 null 或其他默认值
      return null;
    },

   async getListQuery() {
      this.listLoading = true;
    await  getListQuery(this.listQuery).then((response) => {
        this.tableData.records = response.data.records;
        this.tableData.total = response.data.total;
console.log(1,this.tableData);
        this.listLoading = false;
      });
    },
    handleUpdate(row,type) {
      this.dialogType=type
      this.temp = Object.assign({}, row); // copy obj
      this.temp.productList = row.productList?.map((product) => product.id); // 设置已绑定的产品 IDs

      this.listRetailServicePlan;
      this.dialogStatus = "update";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    getListRetailWeightCost() {
      retailWeightCostList("").then((response) => {
        this.listRetailWeightCost = response.data;
      });
    },
    getCineraryUrnList() {
      getCineraryUrnList("").then((response) => {
        console.log(999, response.data);

        this.cineraryUrnListDatas = response.data;
      });
    },
    getListQueryBurial() {//获取员工列表
      getListQueryBurial("").then((response) => {
        console.log(999, response.data);

        this.BurialListDatas = response.data;
      });
    },
    
    getListRetailProduct() {
      retailProductList("").then((response) => {
        this.listRetailProduct = response.data;
      });
    },
    getListRetailServicePlan() {
      this.listLoading = true;
      retailServicePlanList("").then((response) => {
        this.listRetailServicePlan = response.data;
        //         console.log(444,response.data,this.temp.productList)
        this.listLoading = false;

        // if(this.dialogStatus = 'update'){
        //   this.temp.productList=response.data.map(product => product.id); // 设置已绑定的产品 IDs

        // }
      });
    },
    getList() {
      this.listLoading = true;
      retailCustomerListQuery(this.listQuery).then((response) => {
        this.tableData = response.data;
        console.log(this.tableData);
        this.listLoading = false;
      });
    },
    handleFilter() {
      this.listQuery.pageNum = 1;
      this.getListQuery();
    },
    sortChange(data) {
      const { prop, order } = data;
      if (prop === "id") {
        this.sortByID(order);
      }
    },
    sortByID(order) {
      if (order === "ascending") {
        this.listQuery.sort = "+id";
      } else {
        this.listQuery.sort = "-id";
      }
      this.handleFilter();
    },
    resetTemp() {
      this.temp = {
        morticianIds: [], //殡葬师(多个)
        channel: "",
        petVariety: "",
        petSex: "",
        petWeight: "",
        servicePlanId: "",
        servicePlanPrice: 0,
        ashUrnId: "",
        ashUrnPrice:0,
        productIds: "",
        // productPrice: "",//产品价格
        addProductPrice: 0, //加购产品金额
        weightCostId: "",
        weightCostPrice: 0,
        isArrive: "",
        customerAddress: "",
        name: "",
        phone: "",
        petName: "",
        petAge: "",
        petDeadReason: "",
        discount: 0,
        addCarFee: 0,
        totalAmount: 0,
        payType: "",
        remark: "",
        totalAmount:0,//计算出的总价

      };
    },
    handleCreate() {
      this.resetTemp();
      this.temp.morticianIds.push(this.userInfo.id) 
      this.dialogStatus = "create";

      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
      this.dialogFormVisible = true;

    },
    createData() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          this.listLoading = true;
          // this.temp.morticianIds=this.temp.morticianIds.split(",");
          create(this.temp).then(() => {
            this.dialogFormVisible = false;
            this.$notify({
              title: "Success",
              message: "Created Successfully",
              type: "success",
              duration: 2000,
            });
            this.listLoading = false;

            this.getListQuery();
          });
        }
      });
    },
    updateData() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          this.listLoading = true;
          const tempData = Object.assign({}, this.temp);

          // tempData.timestamp = +new Date(tempData.timestamp); // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
          update(tempData).then(() => {
            // this.list.splice(index, 1, this.temp);
            this.dialogFormVisible = false;
            this.$notify({
              title: "Success",
              message: "Update Successfully",
              type: "success",
              duration: 2000,
            });
            this.listLoading = false;
            this.dialogFormVisible = false;

            this.getListQuery();
          });
        }
      });
    },

    handleDelete(row, index) {
      deleteData(row.id).then((response) => {
        this.listLoading = true;
        setTimeout(() => {
          this.listLoading = false;
        }, 1.5 * 1000);
        this.$notify({
          title: "Success",
          message: "Delete Successfully",
          type: "success",
          duration: 2000,
        });
        this.getListQuery();
      });
    },
    handleFetchPv(pv) {
      fetchPv(pv).then((response) => {
        this.pvData = response.data.pvData;
        this.dialogPvVisible = true;
      });
    },
    handleDownload() {
      this.downloadLoading = true;
      exportExcel("");
      this.downloadLoading = false;
    },
    formatJson(filterVal) {
      return this.list.map((v) =>
        filterVal.map((j) => {
          if (j === "timestamp") {
            return parseTime(v[j]);
          } else {
            return v[j];
          }
        })
      );
    },
    getSortClass: function (key) {
      const sort = this.listQuery.sort;
      return sort === `+${key}` ? "ascending" : "descending";
    },
    // ...其他方法
    handlePageChange(newPage) {
      this.listQuery.pageNum = newPage;
      // 如果需要从后端加载数据，此处可以调用
      this.getList();
    },
    handleSizeChange(newSize) {
      this.listQuery.pageSize = newSize;
      // 如果需要从后端加载数据，此处可以调用
      this.getList();
    },
  },
};
</script>
